package com.ebor.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * 继承ThreadPoolExecutor类，覆盖了beforeExecute() 和 afterExecute()
 * 方法来统计线程池的执行情况
 *
 * @author C
 */
public class ThreadPoolAndMonitor extends ThreadPoolExecutor {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolAndMonitor.class);

    private long lastPrintTime;

    /**
     * 保存任务开始执行的时间，当任务结束时，用任务结束时间减去开始时间计算任务执行时间
     */
    private final ConcurrentHashMap<String, Date> startTimes;

    /**
     * 线程池名称
     */
    private final String poolName;

    /**
     * 调用父类的构造方法，并初始化HashMap和线程池名称
     *
     * @param corePoolSize    线程池核心线程数
     * @param maximumPoolSize 线程池最大线程数
     * @param keepAliveTime   线程的最大空闲时间
     * @param unit            空闲时间的单位
     * @param workQueue       保存被提交任务的队列
     * @param threadFactory   线程工厂
     * @param poolName        线程池名称
     */
    public ThreadPoolAndMonitor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
                                TimeUnit unit, BlockingQueue<Runnable> workQueue,
                                ThreadFactory threadFactory, String poolName) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
        this.startTimes = new ConcurrentHashMap<>();
        this.poolName = poolName;
        this.lastPrintTime = System.currentTimeMillis();
    }

    /**
     * 线程池延迟关闭时（等待线程池里的任务都执行完毕），统计线程池情况
     */
    @Override
    public void shutdown() {
        // 统计已执行任务、正在执行任务、未执行任务数量
        logger.info("{} going to shutdown. Executed tasks: {}, Running tasks: {}, Pending tasks: {}",
                this.poolName, this.getCompletedTaskCount(), this.getActiveCount(), this.getQueue().size());
        super.shutdown();
    }

    /**
     * 线程池立即关闭时，统计线程池情况
     */
    @Override
    public List<Runnable> shutdownNow() {
        // 统计已执行任务、正在执行任务、
        logger.info("{} going to immediately shutdown. Executed tasks: {}, Running tasks: {}, Pending tasks: {}",
                this.poolName, this.getCompletedTaskCount(), this.getActiveCount(), this.getQueue().size());
        return super.shutdownNow();
    }

    /**
     * 任务执行之前，记录任务开始时间
     */
    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        startTimes.put(String.valueOf(r.hashCode()), new Date());
    }

    /**
     * 任务执行之后，计算任务结束时间
     */
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        long time = System.currentTimeMillis();
        if ((time - lastPrintTime) < 20000) {
            return;
        }
        lastPrintTime = time;
        String c = Thread.currentThread().getName();
        logger.info("{}->pool-monitor: " + "触发监控的线程：{}, 执行时间：{}," +
                        "总线程数: {}, 核心线程数: {}, 活动线程数: {}, " +
                        "完成任务数: {}, 已安排执行的任务数: {}, 当前排队任务数: {}, 曾经同时进入池中的最大线程数: {}, " +
                        "允许的最大线程数: {},  非核心线程保持活动时间: {}",
                this.poolName, c, time-startTimes.get(String.valueOf(r.hashCode())).getTime(),
                this.getPoolSize(), this.getCorePoolSize(), this.getActiveCount(),
                this.getCompletedTaskCount(), this.getTaskCount(), this.getQueue().size(),
                this.getLargestPoolSize(), this.getMaximumPoolSize(),
                this.getKeepAliveTime(TimeUnit.MILLISECONDS));
    }
}